# database.py
from datetime import datetime
from sqlalchemy.orm import relationship
import redis
from flask_jwt_extended import create_access_token, create_refresh_token
from app.config import Config
from flask_mongoengine import MongoEngine
from mongoengine import Document, StringField,IntField, ObjectIdField, BooleanField, ReferenceField, ListField
db = MongoEngine()
redis_conn = None

def init_redis(app):
    app.redis_conn = redis.Redis(  
        host=app.config.get('REDIS_HOST', 'localhost'),
        port=app.config.get('REDIS_PORT', 6379),
        db=app.config.get('REDIS_DB', 0),
        password=app.config.get('REDIS_PASSWORD'),
        decode_responses=True
    )

class User(Document):
    deviceId = StringField(required=True, unique=True)
    password = StringField(required=True)
    is_device = BooleanField(default=True)
    health_records = ListField(ReferenceField('HealthData'))  # 关联健康数据

class HealthData(Document):
    user = ReferenceField(User, reverse_delete_rule=2)  # 2 表示级联删除
    timestamp = IntField(required=True)
    high = IntField(required=True)
    low = IntField(required=True)
    heartbeat = IntField()
    breathe = IntField()
    walkpace = IntField()
    consume = IntField()
    sleeptime = IntField()
    wearingtime = IntField()
    
    redis_conn = redis.Redis(
    host=Config.REDIS_HOST,
    port=Config.REDIS_PORT,
    db=Config.REDIS_DB,
    password=Config.REDIS_PASSWORD,
    decode_responses=True
)
def save_token_to_cache(identifier, access_token, refresh_token=None):
    redis_conn.setex(
        f"access_token:{access_token}",
        Config.JWT_REDIS_TOKEN_EXPIRES,
        value=str(identifier)
    )
    
    if refresh_token:
        redis_conn.setex(
            f"refresh_token:{refresh_token}",
            Config.JWT_REDIS_TOKEN_EXPIRES,
            value=str(identifier)
        )

def revoke_token_from_cache(token, is_access=True):
    key = f"access_token:{token}" if is_access else f"refresh_token:{token}"
    redis_conn.delete(key)

def check_token_in_cache(token, is_access=True):
    key = f"access_token:{token}" if is_access else f"refresh_token:{token}"
    return redis_conn.exists(key) == 1
def __repr__(self):
        return f'<User {self.deviceId}>'

def init_db(app):
    db.init_app(app)
   
    